// @ts-nocheck

import router from '@/middleware/router'
import crypto from 'crypto'
import fs from 'fs'
import path from 'path'

router.post('/upload', (ctx) => {
  const file = ctx.request.files.file
  const originalFilename = file.originalFilename

  // 获取文件扩展名
  const ext = path.extname(originalFilename)

  // 生成随机文件名（使用时间戳+随机数）
  const randomName = `${Date.now()}-${Math.floor(Math.random() * 10000)}${ext}`

  const uploadPath = path.join(__dirname, '../upload')

  // 创建上传目录（如果不存在）
  if (!fs.existsSync(uploadPath)) {
    fs.mkdirSync(uploadPath, { recursive: true })
  }

  const filePath = path.join(uploadPath, randomName)

  return new Promise((resolve, reject) => {
    const reader = fs.createReadStream(file.filepath)
    const upStream = fs.createWriteStream(filePath)

    upStream.on('finish', () => {
      const buf = fs.readFileSync(filePath)
      const hash = crypto.createHash('md5').update(buf).digest('hex')
      resolve({
        md5: hash,
        filename: randomName,
        originalFilename: originalFilename
      })
    })

    upStream.on('error', (err) => {
      reject(err)
    })

    reader.pipe(upStream)

    ctx.body = {
      code: 200,
      msg: "上传成功",
      data: {
        url: `/upload/${randomName}`,
        filename: randomName
      }
    }
  })
})
